<!--  线 + 柱混合图 -->
<template>
  <div>
    <el-card>
      <template #header>
        <div class="title">
          商品访问图
        </div>
      </template>

      <div :id="id" :class="className" :style="{ height, width }"></div>
    </el-card>
  </div>


</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { getProductStats } from "@/api/product/stats";

let barPVYAxis = [0];
let barCollectYAxis = [0];
let barSaleNumYAxis = [0];
let barUVYAxis = [0];
let barXAxis = ["暂无数据"];

const props = defineProps({
  id: {
    type: String,
    default: "barChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

const downloadEchart = () => {
  // 获取画布图表地址信息
  const img = new Image();
  img.src = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1,
    backgroundColor: "#fff",
  });
  // 当图片加载完成后，生成 URL 并下载
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const link = document.createElement("a");
      link.download = `柱状图.png`;
      link.href = canvas.toDataURL("image/png", 0.9);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };
};

const chart = ref<any>("");
onMounted(async () => {
  const res = await getProductStats();
  if (res.data.barPVYAxis!== null&&res.data.barPVYAxis.length>0) {
    console.log(res.data)
    barPVYAxis = res.data.barPVYAxis;
    barCollectYAxis = res.data.barCollectYAxis;
    barSaleNumYAxis = res.data.barSaleNumYAxis;
    barUVYAxis = res.data.barUVYAxis;
    barXAxis = res.data.barXAxis;
  }

  const options = {
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView : {
          show: true,
          readOnly: true,
          optionToContent: function(opt) {
            var axisData = opt.xAxis[0].data;
            var series = opt.series;
            var table = '<table class="layui-table" style="width:80%;text-align:center"><tbody><tr>'
              + '<td>商品名</td>'
              + '<td>' + series[0].name + '</td>'
              + '<td>' + series[1].name + '</td>'
              + '<td>' + series[2].name + '</td>'
              + '<td>' + series[3].name + '</td>'
              + '</tr>';
            for (var i = 0, l = axisData.length; i < l; i++) {
              table += '<tr>'
                + '<td>' + axisData[i] + '</td>'
                + '<td>' + series[0].data[i] + '</td>'
                + '<td>' + series[1].data[i] + '</td>'
                + '<td>' + series[2].data[i] + '</td>'
                + '<td>' + series[3].data[i] + '</td>'
                + '</tr>';
            }
            table += '</tbody></table>';
            return table;
          }
        },
        saveAsImage: { show: true }
      }
    },
    dataZoom:
      [
        {type: 'inside'},        //用于添加滚轮缩放
        {type:'slider',
          bottom: 25,//下滑块距离x轴底部的距离
          height : 10,
        },  //用于添加滑动条缩放，
      ],
    grid: {
      left: "2%",
      right: "2%",
      bottom: "10%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999",
        },
      },
    },
    legend: {
      x: "center",
      y: "bottom",
      data: ["PV","UV","收藏量","销售量"],
      // padding:[0,50,-10,0],
      textStyle: {
        color: "#999",
      },
    },
    xAxis: [
      {
        type: "category",
        data: barXAxis,
        axisPointer: {
          show: true,
        },
        axisLabel: {
          //x轴文字的配置
          show: true,
          interval: 0, //使x轴文字显示全
          textStyle: {
            color: "rgb(2,61,59)",
          },
          formatter: function (params: any) {
            var newParamsName = "";
            var paramsNameNumber = params.length;
            var provideNumber = 4; //一行显示几个字
            var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
            if (paramsNameNumber > provideNumber) {
              for (var p = 0; p < rowNumber; p++) {
                var tempStr = "";
                var start = p * provideNumber;
                var end = start + provideNumber;
                if (p == rowNumber - 1) {
                  tempStr = params.substring(start, paramsNameNumber);
                } else {
                  tempStr = params.substring(start, end) + "\n";
                }
                newParamsName += tempStr;
              }
            } else {
              newParamsName = params;
            }
            return newParamsName;
          },
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        min: 0,
        axisLabel: {
          formatter: "{value} ",
        },
      },
    ],
    series: [
      {
        name: "PV",
        type: "bar",
        data: barPVYAxis,
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
      },
      {
        name: "UV",
        type: "bar",
        data: barUVYAxis,
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#25d73c" },
            { offset: 0.5, color: "#1bc23d" },
            { offset: 1, color: "#179e61" },
          ]),
        },
      },
      {
        name: "收藏量",
        type: "bar",
        data: barCollectYAxis,
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#e5e104" },
            { offset: 0.5, color: "#ceec09" },
            { offset: 1, color: "#b4e10f" },
          ]),
        },
      },
     {
        name: "销售量",
        type: "bar",
        data: barSaleNumYAxis,
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#d2074e" },
            { offset: 0.5, color: "#e10929" },
            { offset: 1, color: "#ee0732" },
          ]),
        },
      },
    ],
  };

  // 图表初始化
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );

  chart.value.setOption(options);

  // 大小自适应
  window.addEventListener("resize", () => {
    chart.value.resize();
  });
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});
</script>
<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;

  .download {
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}
</style>
